package com.factory.reflect;

import io.netty.channel.ChannelException;
import io.netty.channel.ReflectiveChannelFactory;
import io.netty.util.internal.StringUtil;

import java.lang.reflect.Constructor;
import java.util.Objects;

/**
 * @author wufagang
 * @description
 * @date 2022年07月16日 15:58
 */
public class ReflectiveCarFactory<T extends Car> implements MyCarFactory<T> {
    private final Constructor<? extends T> constructor;

    public ReflectiveCarFactory(Class<? extends T> clazz) {
        assert Objects.nonNull(clazz);
        try {
            this.constructor = clazz.getConstructor();
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException("Class " + StringUtil.simpleClassName(clazz) +
                    " does not have a public non-arg constructor", e);
        }
    }

    @Override
    public T newCar() {
        try {
            return constructor.newInstance();
        } catch (Throwable t) {
            throw new ChannelException("Unable to create Channel from class " + constructor.getDeclaringClass(), t);
        }
    }

    @Override
    public String toString() {
        return StringUtil.simpleClassName(ReflectiveChannelFactory.class) +
                '(' + StringUtil.simpleClassName(constructor.getDeclaringClass()) + ".class)";
    }
}
